<?php

namespace app\astrteam\controller\v1;

use app\astrteam\controller\AstrTeamAuth;
use app\common\lib\Aes;
use app\common\lib\Util;
use think\Db;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\Exception;
use think\exception\DbException;
use think\exception\PDOException;
use think\response\Json;

class TeamData extends AstrTeamAuth
{
    /**
     * 结算统计
     * @return Json
     * @throws Exception
     */
    public function settleList()
    {
        $date = input('date/s', '');
        $page = input('page/d', 1);
        $limit = input('limit/d', 10);
        $appType = input('app_type/d', 0);
        if (!in_array($appType, [1, 2], true))
        {
            return show(config('code.error'), '请求异常，请稍后再试～');
        }
        if (!$date)
        {
            return show(config('code.error'), '请选择查询月份');
        }
        if (date('Y-m', strtotime($date)) !== $date)
        {
            return show(config('code.error'), '月份格式不正确');
        }
        $page = max($page, 1);
        $limit = max($limit, 10);
        // 查询 日期
        $date = (int)date('Ymd', strtotime($date));
        $aesModel = new Aes();
        if ($appType === 1)
        {   // 准了
            $pageData = Db::table('wechat_backup_07_18_14_43_00.zlcr_astr_account_withdrawal_record')->alias('r')->where(['r.team_id' => $this->teamInfo['id'], 'r.date' => $date, 'r.type' => 2])
                ->join('wechat_backup_07_18_14_43_00.zlcr_astr_info ai', 'r.astr_id = ai.astr_id')
                ->join('wechat_backup_07_18_14_43_00.zlcr_astr a', 'r.astr_id = a.id')
                ->field('a.id,ai.name,a.nickname,r.astr_earnings2 zlcr_question_earning,r.astr_earnings4 zlcr_call_earning,r.astr_earnings')
                ->paginate(['list_rows' => $limit, 'page' => $page])->each(function ($item, $key) use ($aesModel)
                {
                    $item['name'] = $aesModel->decryptWithOpenssl($item['name'], 'simulation_astrologer');
                    $item['zyhs_question_earning'] = 0.00;
                    $item['call_earning'] = 0.00;
                    return $item;
                })->toArray();
            $pageData['total_amount'] = '';
            $pageData['remit_status'] = '';
            $pageData['invoice_data'] = '';
            $pageData['invoice_file_url'] = '';
            $pageData['id'] = 0;
            if ($page === 1)
            {
                $withdrawalData = Db::table('wechat_backup_07_18_14_43_00.zlcr_astr_account_withdrawal_record')->where(['team_id' => $this->teamInfo['id'], 'date' => $date, 'type' => 3])
                    ->field('id,astr_earnings,is_withdrawal,invoice_url')->find();
                $pageData['total_amount'] = $withdrawalData['astr_earnings'];
                $pageData['remit_status'] = (int)$withdrawalData['is_withdrawal'];
                $pageData['id'] = (int)$withdrawalData['id'];
                $pageData['invoice_data'] = "名称：北京星座女神文化传媒有限公司\n社会统一代码：9111 0105 3181 9744 80\n地址电话：北京市朝阳区高碑店乡金家村中街8号C-3009  010-85164828\n开户行及账号：招商银行股份有限公司北京自贸试验区商务中心区支行\n银行账户：1109 1397 4110 802";
                if ($withdrawalData['invoice_url'])
                {
                    $pageData['invoice_file_url'] = $this->getOssPrivateUrl($withdrawalData['invoice_url']);
                }
            }
        } else
        {   // 准有好事
            $pageData = Db::table('good_wechat.zyhs_astr_account_withdrawal_record')->alias('r')->where(['r.team_id' => $this->teamInfo['id'], 'r.date' => $date, 'r.type' => 2])
                ->join('wechat_backup_07_18_14_43_00.zlcr_astr_info ai', 'r.astr_id = ai.astr_id')
                ->join('wechat_backup_07_18_14_43_00.zlcr_astr a', 'r.astr_id = a.id')
                ->field('a.id,ai.name,a.nickname,r.astr_earnings1 call_earning,r.astr_earnings2 zyhs_question_earning,r.astr_earnings')
                ->paginate(['list_rows' => $limit, 'page' => $page])->each(function ($item, $key) use ($aesModel)
                {
                    $item['name'] = $aesModel->decryptWithOpenssl($item['name'], 'simulation_astrologer');
                    $item['zlcr_question_earning'] = '0.00';
                    $item['zlcr_call_earning'] = '0.00';
                    return $item;
                })->toArray();
            $pageData['total_amount'] = '';
            $pageData['remit_status'] = '';
            $pageData['invoice_data'] = '';
            $pageData['invoice_file_url'] = '';
            $pageData['id'] = 0;
            if ($page === 1)
            {
                $withdrawalData = Db::table('good_wechat.zyhs_astr_account_withdrawal_record')->where(['team_id' => $this->teamInfo['id'], 'date' => $date, 'type' => 3])
                    ->field('id,astr_earnings,is_withdrawal,invoice_url')->find();
                $pageData['total_amount'] = $withdrawalData['astr_earnings'];
                $pageData['remit_status'] = (int)$withdrawalData['is_withdrawal'];
                $pageData['id'] = (int)$withdrawalData['id'];
                $pageData['invoice_data'] = "名称：北京好准科技有限公司\n社会统一代码：9111 0116 MACG LCLW 63\n地址：北京市怀柔区青春路54号3幢101室（集群注册）\n开户行：中信银行北京三里屯支行\n开户账号：8110701013402584210";
                if ($withdrawalData['invoice_url'])
                {
                    $pageData['invoice_file_url'] = $this->getOssPrivateUrl($withdrawalData['invoice_url']);
                }
            }
        }

        return show(config('code.success'), '请求成功', $pageData);
    }

    /**
     * 成员详情
     * @return Json
     * @throws Exception
     */
    public function userEarningList()
    {
        $astrId = input('astr_id/d', 0);
        $date = input('date/s', '');
        $page = input('page/d', 1);
        $limit = input('limit/d', 10);
        $appType = input('app_type/d', 0);  // 1=>准了 2=>准有好事
        $questionType = input('question_type/d', 0);
        if (!in_array($appType, [1, 2], true))
        {
            return show(config('code.error'), '请求异常，请稍后再试～');
        }
        if (($appType === 1 && !in_array($questionType, [2, 3], true)) || ($appType === 2 && !in_array($questionType, [3, 4], true)))
        {
            return show(config('code.error'), '请求异常，请稍后再试～');
        }
        if (!$date)
        {
            return show(config('code.error'), '请选择查询月份');
        }
        if (date('Y-m', strtotime($date)) !== $date)
        {
            return show(config('code.error'), '月份格式不正确');
        }
        $page = max($page, 1);
        $limit = max($limit, 10);
        // $startTime = strtotime($date);
        // $endTime = strtotime($date . ' +1 month');
        $dataTime = (int)date('Ymd', strtotime($date));
        $questionTypeName = [
            1 => '星盘',
            2 => '骰子',
            3 => '塔罗',
        ];
        if ($questionType == 2)
        {
            $resPageData = Db::table('wechat_backup_07_18_14_43_00.zlcr_astr_account_record')->alias('r')->join('wechat_backup_07_18_14_43_00.zlcr2_astr_tasks t', 'r.qid = t.qid AND r.astr_id=t.astr_id')
                ->where([
                    'r.astr_id' => $astrId,
                    'r.team_id' => $this->teamInfo['id'],
                    'r.question_type' => 2, // 2=>问答 3=>连线咨询 4=>准有好事-问答
                    'r.type' => ['in', [1, 4, 5]],
                    'r.status' => 1,
                    // ])->whereTime('r.create_time', '>=', $startTime)->whereTime('r.create_time', '<', $endTime)->order('r.create_time desc')
                ])->where('r.withdrawal_month', $dataTime)->order('r.create_time desc')
                ->field('r.good_amount as amount,r.amount as earning,t.qid as task_id,t.question_type,r.create_time end_time,r.type as status')
                ->paginate(['list_rows' => $limit, 'page' => $page])->each(function ($item, $key) use ($questionTypeName)
                {
                    $item['end_time'] = date('Y.m.d H:i', $item['end_time']);
                    $item['question_type_name'] = $questionTypeName[$item['question_type']];
                    $item['add_question_num'] = Db::table('good_wechat.zyhs_user_add_question')->where(['task_id' => $item['task_id'], 'status' => 4])->count();
                    switch ($item['status'])
                    {
                        case 4:
                            $item['earning'] = '-' . $item['earning'] . '元  扣除收益';
                            break;
                        case 5:
                            $item['earning'] = $item['earning'] . '元  操作纠正';
                            break;
                        default:
                            $item['earning'] = $item['earning'] . '元';
                    }
                    unset($item['question_type']);
                    return $item;
                })->toArray();
        } elseif ($questionType == 4)
        {
            $resPageData = Db::table('wechat_backup_07_18_14_43_00.zlcr_astr_account_record')->alias('r')->join('good_wechat.zyhs_astr_tasks t', 'r.qid = t.id')
                ->where([
                    'r.astr_id' => $astrId,
                    'r.team_id' => $this->teamInfo['id'],
                    'r.question_type' => 4, // 2=>问答 3=>连线咨询 4=>准有好事-问答
                    'r.type' => ['in', [1, 4, 5]],
                    'r.status' => 1,
                    // ])->whereTime('r.create_time', '>=', $startTime)->whereTime('r.create_time', '<', $endTime)->order('r.create_time desc')
                ])->where('r.withdrawal_month', $dataTime)->order('r.create_time desc')
                ->field('r.good_amount as amount,r.amount as earning,t.id as task_id,t.question_type,r.create_time end_time,r.type as status')
                ->paginate(['list_rows' => $limit, 'page' => $page])->each(function ($item, $key) use ($questionTypeName)
                {
                    $item['end_time'] = date('Y.m.d H:i', $item['end_time']);
                    $item['question_type_name'] = $questionTypeName[$item['question_type']];
                    $item['add_question_num'] = Db::table('good_wechat.zyhs_user_add_question')->where(['task_id' => $item['task_id'], 'status' => 4])->count();
                    switch ($item['status'])
                    {
                        case 4:
                            $item['earning'] = '-' . $item['earning'] . '元  扣除收益';
                            break;
                        case 5:
                            $item['earning'] = $item['earning'] . '元  操作纠正';
                            break;
                        default:
                            $item['earning'] = $item['earning'] . '元';
                    }
                    unset($item['question_type']);
                    return $item;
                })->toArray();
        } else
        {   // 连线咨询
            // $appType = 1=>准了 2=>准有好事
            $questionType = $appType === 1 ? 5 : 3;
            $resPageData = Db::table('wechat_backup_07_18_14_43_00.zlcr_astr_account_record')->alias('r')->join('good_wechat.zyhs_consult_chat_rtc_record cc', 'r.gid = cc.id')
                ->where([
                    'r.astr_id' => $astrId,
                    'r.team_id' => $this->teamInfo['id'],
                    'r.question_type' => $questionType, // 2=>问答 3=>连线咨询 4=>准有好事-问答
                    'r.type' => 1,
                    'r.status' => 1,
                    // ])->whereTime('r.create_time', '>=', $startTime)->whereTime('r.create_time', '<', $endTime)->order('r.create_time desc')
                ])->where('r.withdrawal_month', $dataTime)->order('r.create_time desc')
                ->field('r.good_amount as amount,r.proportion as percent,r.amount as earning,cc.chat_detail_id as task_id,cc.eff_duration as duration,cc.end_time,cc.extend,cc.unit_price as price')
                ->paginate(['list_rows' => $limit, 'page' => $page])->each(function ($item, $key)
                {
                    $extend = json_decode($item['extend'], true);
                    $serviceNum = $extend['service_num'] ?? 1;
                    switch (true)
                    {
                        case $serviceNum === 1:
                            $type = '普通';
                            break;
                        case $serviceNum >= 2 && $serviceNum <= 5:
                            $type = '复购（次数≥2次且≤5次）';
                            break;
                        case $serviceNum >= 6 && $serviceNum <= 10:
                            $type = '复购（次数≥6次且≤10次）';
                            break;
                        default:
                            $type = '复购（次数≥11次）';
                    }
                    $item['type'] = $type;
                    $item['end_time'] = date('Y.m.d H:i', $item['end_time']);
                    $item['price'] = $item['price'] / 10;
                    $item['duration'] = Util::secondToMinute($item['duration']);
                    $item['percent'] = ($item['percent'] * 100) . '%';
                    $item['earning'] = $item['earning'] . '元';
                    unset($item['extend']);
                    return $item;
                })->toArray();
        }

        return show(config('code.success'), '请求成功', $resPageData);
    }

    /**
     * 上传发票信息
     * @return Json
     * @throws Exception
     */
    public function setInvoice()
    {
        $invoiceUrl = input('invoice_url/s', '');
        $id = input('id/d', 0);
        $appType = input('app_type/d', 0);  // 1=>准了 2=>准有好事
        if (!in_array($appType, [1, 2], true))
        {
            return show(config('code.error'), '请求异常，请稍后再试～');
        }
        if (empty($invoiceUrl))
        {
            return show(config('code.error'), '服务异常，发票信息错误');
        }
        if ($appType === 1)
        {
            $withdrawalData = Db::table('wechat_backup_07_18_14_43_00.zlcr_astr_account_withdrawal_record')->where(['team_id' => $this->teamInfo['id'], 'id' => $id, 'type' => 3])
                ->field('id,date,invoice_url')->find();
        } else
        {
            $withdrawalData = Db::table('good_wechat.zyhs_astr_account_withdrawal_record')->where(['team_id' => $this->teamInfo['id'], 'id' => $id, 'type' => 3])
                ->field('id,date,invoice_url')->find();
        }

        if (!$withdrawalData)
        {
            return show(config('code.error'), '服务异常，请稍后再试');
        }
        // 取上个月的日期
        $lastMonth = date('Ym01', strtotime('-1 month'));
        if ($withdrawalData['date'] != $lastMonth)
        {
            return show(config('code.error'), '服务异常，只能修改上个月的发票信息');
        }

        if ($appType === 1)
        {   // 准了
            $res = Db::table('wechat_backup_07_18_14_43_00.zlcr_astr_account_withdrawal_record')->where(['id' => $id])->update(['invoice_url' => $invoiceUrl]);
        } else
        {   // 准有好事
            $res = Db::table('good_wechat.zyhs_astr_account_withdrawal_record')->where(['id' => $id])->update(['invoice_url' => $invoiceUrl]);
        }
        if ($res)
        {
            return show(config('code.success'), '发票上传成功');
        } else
        {
            return show(config('code.error'), '服务异常，上传发票失败');
        }
    }
}